
package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.AwardRecord;
import com.ruoyi.business.common.config.AwardConfig;
import com.ruoyi.business.domain.ActivityAggregateVo;
import com.ruoyi.business.domain.DistributionAwardRecord;
import com.ruoyi.business.mapper.DistributionAwardRecordMapper;
import com.ruoyi.business.service.IAwardService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author cyh
 * @date 2022/6/25 10:48 上午
 */
@Slf4j
@Service
public class AwardServiceImpl implements IAwardService {

    @Resource
    RestTemplate restTemplate;

    @Autowired
    AwardConfig awardConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private DistributionAwardRecordMapper distributionAwardRecordMapper;

    //奖励活动配置详情缓存key
    public static final String AWARD_ACTIVITY_DETAIL = "AWARD_ACTIVITY_DETAIL";

    @Override
    public ActivityAggregateVo getAwardActivityDetail() {
        log.info("查询奖励活动详情 >>> ");
        ActivityAggregateVo activityAggregateVo = redisCache.getCacheObject(AWARD_ACTIVITY_DETAIL);
        if (activityAggregateVo != null) {
            log.info("返回redis缓存信息 return :{}", JSONObject.toJSONString(activityAggregateVo));
            return activityAggregateVo;
        }
        JSONObject resJson = restTemplate.getForObject(awardConfig.getBaseUrl() + "/activity/detail", JSONObject.class);
        log.info("查询奖励活动详情 return :{}", resJson.toString());
        int resCode = resJson.getInteger("code");
        if (resCode == 200 && Func.isNotEmpty(resJson.get("data"))) {
            activityAggregateVo = resJson.getObject("data", ActivityAggregateVo.class);
            redisCache.setCacheObject(AWARD_ACTIVITY_DETAIL, activityAggregateVo, 5, TimeUnit.MINUTES); //缓存5分钟
        }
        return activityAggregateVo;
    }

    @Override
    public BigDecimal getAwardAmountSum(String userId) {
        log.info("查询用户奖励金额总数 >>> userId = {}", userId);
        String url = awardConfig.getBaseUrl() + "/userId/amountSum".replace("userId", userId);
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        log.info("查询用户奖励金额总数 return :{}", forObject.toString());
        return forObject.getBigDecimal("data");
    }

    @Override
    public JSONObject getUserRecord(String userId) {
        log.info("查询用户奖励记录 >>> userId = {}", userId);
        String url = awardConfig.getBaseUrl() + "/record/" + userId;
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        log.info("查询用户奖励记录 return :{}", forObject.toString());
        return forObject.getJSONObject("data");
    }

    @Override
    public JSONObject getUserInviteRecord(String userId) {
        log.info("查询用户邀请记录 >>> userId = {}", userId);
        String url = awardConfig.getBaseUrl() + "/record/invite/" + userId;
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        log.info("查询用户邀请记录 return:{}", forObject.toString());
        return forObject.getJSONObject("data");
    }

    @Override
    public int rewardedTotal(String bvnAccount, Long actId, Long awardConfigId) {
        log.info("查询奖励总数 >>> bvnAccount = {}, actId = {}, awardConfigId = {}", bvnAccount, actId, awardConfigId);
        String url = awardConfig.getBaseUrl() + "/record/rewardedTotal?bvnAccount=" + bvnAccount + "&actId=" + actId + "&awardConfigId=" + awardConfigId;
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        log.info("查询奖励总数 return:{}", forObject.toString());
        return Optional.ofNullable(forObject.getInteger("data")).orElse(0);
    }

    @Override
    public void awardDistribution(List<AwardRecord> recordList, Long recordId) {
        log.info("开始发放活动奖励 >>> recordList = {}", JSON.toJSONString(recordList));
        DistributionAwardRecord distributionAwardRecord = new DistributionAwardRecord();
        distributionAwardRecord.setId(recordId);
        distributionAwardRecord.setParams(JSON.toJSONString(recordList));
        distributionAwardRecordMapper.updateById(distributionAwardRecord);
        String url = awardConfig.getBaseUrl() + "/distribution";
        //返回事务执行状态
        JSONObject forObject = restTemplate.postForObject(url, recordList, JSONObject.class);
        log.info("开始发放活动奖励 return:{}", forObject.toString());
        if (forObject != null && StringUtils.isNotEmpty(forObject.getString("data"))) { //请求响应成功
            distributionAwardRecord = new DistributionAwardRecord();
            distributionAwardRecord.setId(recordId);
            distributionAwardRecord.setState("1");
            distributionAwardRecord.setRemark(forObject.getString("data"));
            distributionAwardRecordMapper.updateById(distributionAwardRecord);
        }
    }

    public static void main(String[] args) {
        RestTemplate tpl = new RestTemplate();
        String url = "http://localhost:8900/award/";
        url = url + "record/rewardedTotal?bvnAccount=1133&activityTypeValue=213123&eventValue=2";
        JSONObject body = tpl.getForObject(url, JSONObject.class);
        System.out.println(body.toString());
    }
}
